package com.sbhc.httpclient.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.util.*;

/**
 * @Author fyy
 * @Description HttpClient工具类
 * @Date 2020/5/18 15:56
 */
public class HttpOldUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpOldUtil.class);

    /**
     * @Author fyy
     * @Description get 请求
     * @param url 请求地址
     * @param param 参数集
     * @param headers 头部参数
     * @Date 2020/5/18 16:11
     */
    public static String httpGet(String url, Map<String, String> param, Map<String, String> headers){
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000)
                .build();
        String result = "";
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if(null != param){
                for (String key : param.keySet()) {
                    builder.addParameter(key,param.get(key));
                }
            }
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setConfig(requestConfig);
            httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
            if(null != headers){
                for (String key : headers.keySet()) {
                    httpGet.addHeader(key,headers.get(key));
                }
            }
            response = httpClient.execute(httpGet);
            //判断返回状态是否为200
            if(response.getStatusLine().getStatusCode() == 200){
                result = EntityUtils.toString(response.getEntity());
            }
        } catch (Exception e) {
            logger.error("http请求异常：{}",e.getMessage());
        }finally {
            try {
                if(null != response){
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                logger.error("http请求流关闭异常：{}",e.getMessage());
            }
        }
        return result;
    }

    /**
     * @Author fyy
     * @Description post 请求
     * @param url 请求地址
     * @param param 参数集 Map
     * @Date 2020/5/18 16:50
     */
    public static String httpPostByParamMap(String url, Map<String, String> param){
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000)
                .build();
        String result = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            if(null != null){
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key,param.get(key)));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            //执行http请求
            response = httpClient.execute(httpPost);

            if(response.getStatusLine().getStatusCode() == 200){
                result = EntityUtils.toString(response.getEntity(),"utf-8");
            }
        } catch (Exception e) {
            logger.error("http post请求异常：{}",e.getMessage());
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                logger.error("http post请求关闭流异常：{}",e.getMessage());
            }
        }

        return result;
    }

    /**
     * @Author fyy
     * @Description post 请求
     * @param url 请求地址
     * @param json 参数集 json
     * @Date 2020/5/18 16:50
     */
    public static String httpPostByParamJson(String url, String json){
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000)
                .build();
        String result = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);

            if(response.getStatusLine().getStatusCode() == 200){
                result = EntityUtils.toString(response.getEntity(),"utf-8");
            }
        } catch (Exception e) {
            logger.error("http post请求异常：{}",e.getMessage());
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                logger.error("http post请求关闭流异常：{}",e.getMessage());
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String url = "http://miaowuyun.com:8081/api/department/getAll?departmentId=1";
        Map<String,String> param = new HashMap<String,String>();
        param.put("departmentId","1");
        Map<String,String> headers = new HashMap<String,String>();
        System.out.println(httpGet(url,param,headers));

        String url2 = "http://www.miaowuyun.com:8081/api/msg/sendToOneByPhone";
        Map<String,Object> param2 = new HashMap<String,Object>();
        JSONObject obj = new JSONObject();
        obj.put("phone","18701199803");
        obj.put("sendToAll",0);
        obj.put("msgType","link");
        obj.put("title","消息通知标题");
        obj.put("text","消息通知标题");
        obj.put("templateId",1);
        obj.put("taskId", UUID.randomUUID().toString().replaceAll("-",""));
        obj.put("contentPicUrl","1111");
        System.out.println(httpPostByParamJson(url2,obj.toJSONString()));

    }

}
